package cn.meetingroom.controller;

import cn.meetingroom.model.Notice;
import cn.meetingroom.model.User;
import cn.meetingroom.service.NoticeService;
import org.codehaus.jackson.map.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/NoticeServlet/*")
public class NoticeServlet extends BaseServlet {
    private NoticeService noticeService = new NoticeService();
    ObjectMapper mapper = new ObjectMapper();

    public void addNotice(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Notice notice  = new Notice();
        request.setCharacterEncoding("UTF-8");
        User admin = (User)request.getSession().getAttribute("admin");
        notice.setnTitle(request.getParameter("nTitle"));
        notice.setcUserId(admin.getId());
        notice.setnText(request.getParameter("nText"));
        noticeService.addNotice(notice);

        response.sendRedirect("/MeetingRoom/statics/admin/NoticeList.html");
    }

    public void delNotice(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("nId"));
        noticeService.delNotice("noticeId",id);
    }

    public void getNoticeList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        mapper.writeValue(response.getWriter(),noticeService.getNoticeList());
    }

    public void getUnreadNum(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");

        mapper.writeValue(response.getWriter(),noticeService.getUnreadNum(user.getId()));
    }

    public void upUserTime(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute("user");

        noticeService.upReadTime(user.getId());
    }
}
